package gs.android.calcfeud;

import java.util.GregorianCalendar;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class Dice extends Sprite {
	private Rect src, dst;
	
	private boolean rolling;
	private long started, end;
	private int eyes;

	public Dice(float x, float y, float height, float width, int eyes, Bitmap bitmap) {
		super(x, y, height, width, bitmap);
		this.eyes = eyes;
		this.rolling = false;
		
		src = new Rect(0, 0, 128, 128);
		dst = new Rect((int)x, (int)y, (int)(x + getWidth()), (int)(y + getHeight()));
		started = GregorianCalendar.getInstance().getTimeInMillis();
		end = started;
	}

	public boolean isRolling() {
		return rolling;
	}

	public void setRolling(boolean rolling) {
		this.rolling = rolling;
	}

	@Override
	public void onDraw(Canvas c, int delta) {
		long time = 0;
		
		if (rolling)
			time = GregorianCalendar.getInstance().getTimeInMillis() - started;
		else
			time = end - started;
		
		int index = (int)((time / ((1000 / eyes) +1 )) % eyes);
		src.left = index * (getBitmap().getWidth() / eyes);
		src.right = (index + 1) * (getBitmap().getWidth() / eyes);
		
		c.drawBitmap(getBitmap(), src, dst, null);
	}
	
	public void roll() {
		rolling = true;
		started = GregorianCalendar.getInstance().getTimeInMillis();
	}
	
	public void stop() {
		rolling = false;
		end = GregorianCalendar.getInstance().getTimeInMillis();
	}
}